package com.irdstudio.bsp.executor.core.plugin.migrate;

import com.irdstudio.bsp.executor.core.plugin.migrate.dao.*;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.util.*;

/**
 * <p>migrateTableDataUtil: 迁移表映射数据<p>
 * @author cjw
 * @date 2020-11-04
 */
public class migrateTableDataUtil extends BaseUtil{


	private static Logger logger = LoggerFactory.getLogger(migrateTableDataUtil.class);
	/**
	 * 表数据迁移插件实现类接口
	 * params：tableMapping映射表配置{}，fieldMappingList映射字段[]
	 */
	public boolean datamigration(MigrateTableMapping tableMapping, List<MigrateFieldMapping> fieldMappingList, Connection conn, Connection source_conn, Connection target_conn){
		boolean result=true;

		try {
			String ybSelectSql=	"";
			//需要转换字典的字段集合start 组成查询字典转换关系in条件；
			StringBuffer sourceFieldCode=new StringBuffer("(");
			StringBuffer targetFieldCode=new StringBuffer("(");
			//保存映射字段类型为数据字典的记录
			List<Map> strList=new ArrayList<>();
			StringBuffer ziduan=new StringBuffer("(");
			StringBuffer crvalue=new StringBuffer("(");
			StringBuffer Nziduan=new StringBuffer("");
			for (int i = 0; i <fieldMappingList.size() ; i++) {
				MigrateFieldMapping fieldMapping=fieldMappingList.get(i);
				crvalue.append("?,");
				ziduan.append(fieldMapping.getTargetFieldCode()+",");
				Nziduan.append(fieldMapping.getSourceFieldCode()+",");
				if(fieldMapping.getFieldMappingRule().equals("R03")){
					strList.add(ObjecttoMap(fieldMapping));
					sourceFieldCode.append("'"+fieldMapping.getSourceFieldCode()+"'"+",");
					targetFieldCode.append("'"+fieldMapping.getTargetFieldCode()+"'"+",");
				}
			}
			//end
			//字典转换关系字段映射记录集合
			List<MigrateDictRelation> drRelatioNList=new ArrayList<>();
			MigrateDictRelationDao migrateDictRelationDao=new MigrateDictRelationDao(conn);
			//查询字典选项
			drRelatioNList=migrateDictRelationDao.relationWhereString(sourceFieldCode,targetFieldCode);
			StringBuffer relationId=new StringBuffer("(");
			//获取要查询转换关系表的relationId集合
			for (int i = 0; i < drRelatioNList.size(); i++) {
				MigrateDictRelation migrateDictRelation=drRelatioNList.get(i);
				relationId.append("'"+migrateDictRelation.getRelationId()+"'"+",");
			}

			//字典转换关系字段选项记录集合
			List<MigrateDictMapping> drmappinglist=new ArrayList<>();
			MigrateDictMappingDao migrateDictMappingDao=new MigrateDictMappingDao(conn);
			drmappinglist=migrateDictMappingDao.queryDictionaryTransformRelationalFieldOptionRecordCollection(relationId);
			//要插入目标表的数据集合
			List<Map> targetlist=new ArrayList<>();
			//判断配置进行源表查询sql组合
			//S代表sql查询源表数据否则整表查数据
			if(!tableMapping.getTableMappingWay().equals("T")){
				//获取配置的源表sql
				ybSelectSql=tableMapping.getSourceSql();
			}else{
				ybSelectSql="select  " +
						Nziduan.substring(0,Nziduan.length() - 1)+
						" from "+ tableMapping.getSourceTableCode();
			}
			//end
			//sql查询源表数据集合
			List<Map> ybList=new ArrayList<>();
			MigrationtabledataUtilDao migrationtabledataUtilDao=new MigrationtabledataUtilDao(source_conn);
			logger.info("sql查询源表数据sql:"+ybSelectSql);
			ybList=migrationtabledataUtilDao.selecttablelist(ybSelectSql);
			//处理要迁移到目标表的数据
			for (int i = 0; i <ybList.size() ; i++) {
				Map targetMap=new LinkedHashMap();
				Map ybMap=ybList.get(i);
				//循环所有配置字段进行源表数据跟目标表数据进行匹配
				for (int f = 0; f < fieldMappingList.size(); f++) {
					MigrateFieldMapping fieldMap=fieldMappingList.get(f);
					//字段是数据字典的情况下需要转换
					if(fieldMap.getFieldMappingRule().equals("R03")){
						String key=fieldMap.getSourceFieldCode();
						//需要匹配的字典转换中的字段
						String relationid="";
						//循环字典转换关系里的字段找到要转换字典的那一条记录保存id
						for (int r = 0; r < drRelatioNList.size(); r++) {
							MigrateDictRelation migrateDictRelation= drRelatioNList.get(r);
							//通过源字段code目标字段code找到对应的转换关系字段
							if(fieldMap.getSourceFieldCode().equals(migrateDictRelation.getSourceFieldCode())&&
									fieldMap.getTargetFieldCode().equals(migrateDictRelation.getTargetFieldCode())&&
									tableMapping.getSourceTableCode().equals(migrateDictRelation.getSourceTableCode())&&
									tableMapping.getTargetTableCode().equals(migrateDictRelation.getTargetTableCode())){
								relationid=migrateDictRelation.getRelationId();
							}
						}
						String value="";
						List<MigrateDictMapping> dplist=new ArrayList<>();
						//循环字典选项集合找到对应字段的字典选项
						for (int dp = 0; dp < drmappinglist.size(); dp++) {
							MigrateDictMapping migrateDictMapping=drmappinglist.get(dp);
							if(migrateDictMapping.getRelationId().equals(relationid)){
								dplist.add(migrateDictMapping);
							}
						}
						//循环选项匹配复制到目标表字段对应的字典值
						for (int j = 0; j < dplist.size(); j++) {
							MigrateDictMapping dpobj=dplist.get(j);
							if(MapUtils.getString(ybMap,key,"").equals(dpobj.getSourceOptionCode())){
								value=	dpobj.getTargetOptionCode();
							}
						}
						//将处理好的数据添加到目标数据集合list
						targetMap.put(fieldMap.getTargetFieldCode(),value);
					}else{
						String key=fieldMap.getSourceFieldCode();
						targetMap.put(fieldMap.getTargetFieldCode(),MapUtils.getString(ybMap,key,""));
					}
				}
				targetlist.add(targetMap);
			}
			//插入目标数据sql语句
			MigrateTableMappingDao migrateTableMappingDao = new MigrateTableMappingDao(target_conn);
			boolean datamigration = migrateTableMappingDao.insertTheTargetDataSQLStatement(tableMapping,ziduan,crvalue,targetlist);
			result=	datamigration;
		} catch (Exception e) {
			result = false;
			logger.error("表数据迁移执行出错！", e);
		}
		return  result;
	}
}
